local gamelib = require "club.threecard.gamelib"
local slotlib = require "club.threecard.slotlib"
local components = slotlib.require "components"

local slot_system = slotlib.systems.slot_system
local class = gamelib.entitas.class
local Matcher = gamelib.entitas.Matcher
local GroupEvent = gamelib.entitas.GroupEvent


local freespin_system = class("freespin_system", slot_system)

function freespin_system:ctor(context, ingame)
    freespin_system.super.ctor(self, context, ingame);
    self.freespin_fx = slotlib.require("widget.FreeSpinFX").new();
end

function freespin_system:initialize()
    self.freespin_fx:load();
    local fx_root = self.ingame.fx_root;
    self.freespin_fx:set_parent(fx_root);
    self.freespin_fx:hide();
    self.context.machine:replace(components.freespin_component, 0, false, false, 0);
end

function freespin_system:get_trigger()
    return {{Matcher({components.freespin_component}), GroupEvent.ADDED | GroupEvent.UPDATE}};
end

function freespin_system:filter(entity)
    return entity:has(components.frames_component) and entity:has(components.freespin_component)
end

local function filter_frame(frames)
    local ret = {}    

    for _, frame in ipairs(frames) do
        if frame.type == slotlib.frame_type.line_hit then
            table.insert(ret, frame);
        end
    end

    return ret;
end

function freespin_system:execute(entitas)
    if entitas:size() ~= 1 then
        gamelib.log.error("数据错误，结果组件不可能>1")
        return;
    end

    entitas:foreach(function(e)
        local freespin_component = e:get(components.freespin_component)
        local times = freespin_component.left_times;
        local is_trigger = freespin_component.is_trigger;
        freespin_component.is_trigger = false;

        if not is_trigger then
            return;
        end

        self.freespin_fx:show();
        self:wait(1.4);
        self.freespin_fx:hide();

        if not freespin_component.in_free then
            self.ingame.hud:on_free();
        end

        freespin_component.in_free = true;

        -- huuuge是free的时候必须自己点，
        -- 先改成 如果是自动不需要自己点
        --e:replace(components.interrupt_component);
    end)
end

function freespin_system:cleanup()
    if self.context.machine:has(components.interrupt_component) then
        self.context.machine:remove(components.interrupt_component);
    end
end

function freespin_system:skip()

end

return freespin_system